/*
 * GWSocketHandler.cpp
 *
 *  Created on: 2016-5-4
 *      Author: Administrator
 */

#include "GWSocketHandler.h"
#include "utils.h"

/**
 * 头含帧长度的解码器
 */
GWSocketHandler::GWSocketHandler(int _lenIndex, int _lenSize) :
		SocketHandler() {
	LOGI("  ");
	mLenIndex =_lenIndex;
	mLenSize = _lenSize;
}
GWSocketHandler::GWSocketHandler() :
		SocketHandler() {
	LOGI("  ");
	mLenIndex = 0;
	mLenSize = 0;
}

GWSocketHandler::~GWSocketHandler() {

}
int GWSocketHandler::doDecode(SocketChannel* socketChanel, char *buf, int size){
	if(size<=0){
		return size;
	}
	LOGI("buf address:%p  bufferSize:%d", buf, size);
	int gwHeaderSize = sizeof(GWHeader);
	if (size < gwHeaderSize) {
		LOGI("RECV data size %d<sizeof(GWHeader %d)", size, gwHeaderSize);
		return 0;
	}
	GWHeader* header = (GWHeader*) buf;
	LOGI("header size:%d,CMD:%d ,errCode %d", header->size, header->cmd,header->fromID);
	if(size>=header->size){
		if(header->size<=BUF_MAX_SIZE){
			return socketChanel->recvData(buf,header->size);
		}
	}
	return 0;
}
int GWSocketHandler::doEncode(int socketfd, char *buf, int size) {
	if(mLenSize<=0||mLenSize!=2||mLenSize!=4||mLenSize!=8){
		LOGE("encode fail;mLenSize:%d", mLenSize);
		return 0;
	}
	if(buf==NULL||size<=0||size<mLenSize){
		LOGE("encode fail,buf :%p,size:%d",buf, size);
		return 0;
	}
	memcpy(buf+mLenIndex,&size,mLenSize);
	return mLenSize;
}
int GWSocketHandler::doEncode(int socketfd, char *buf, int size, int cmd,
		char* outBuf, int outBufSize) {
	int lenFieldHeader = sizeof(GWHeader);
	if (outBufSize < (lenFieldHeader + size)) {
		LOGE(" outBufSize<(lenFieldHeader+size) ");
		return ERR_ILL_PARMS;
	}
	GWHeader header;
	memset(&header, 0, lenFieldHeader);
	header.cmd = cmd;
	header.size = lenFieldHeader + size;
	LOGI(" onDataOut size is %d", header.size);
	char temp[BUF_MAX_SIZE];
	memcpy(temp, buf, size);
	memcpy(outBuf, &header, lenFieldHeader);
	memcpy(outBuf + lenFieldHeader, temp, size);
	return header.size;
}

int GWSocketHandler::send(char* buf, int size) {
	LOGI("  ");
	return 0;
}
